package com.yb.guigu.pick.security.config;

import com.yb.guigu.pick.security.bean.WhiteListProperties;
import com.yb.guigu.pick.security.filter.GuiguPickAuthenticationProcessingFilter;
import com.yb.guigu.pick.security.filter.GuiguPickUserAuthenticationFilter;
import com.yb.guigu.pick.security.generator.*;
import com.yb.guigu.pick.security.provider.GuiguPickUserCodeAuthenticationProvider;
import com.yb.guigu.pick.security.provider.GuiguPickUserPasswordAuthenticationProvider;
import com.yb.guigu.pick.security.handler.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/29 17:24
 * FileName: AuthServerConfig
 * Description:
 */

@Configuration
@EnableWebSecurity
@Slf4j
@EnableMethodSecurity(securedEnabled = true,proxyTargetClass = true)
@EnableConfigurationProperties(WhiteListProperties.class)
@ComponentScan("com.yb.guigu.pick.security.provider")
public class AuthServerConfig {

    @Autowired
    WhiteListProperties whiteListProperties;

    @Value("${spring.application.name:UNKNOWN}")
    private String appName;


    @Autowired
    UserDetailsService userDetailsService;

    @Bean
    AuthenticationSuccessHandler successHandler(){
        return new GuiguPickLoginSuccessHandler();
    }

    @Bean
    AuthenticationFailureHandler failureHandler(){
        return new GuiguPickLoginFailedHandler();
    }

    @Bean
    AuthenticationEntryPoint authenticationEntryPoint(){
        return new GuiguPickAuthenticationEntryPoint()  ;
    }


    @Bean
    AccessDeniedHandler accessDeniedHandler(){
        return new GuiguPickAccessDeniedHandler();
    }


    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration,List<AuthenticationProvider> providers) throws Exception {
        ProviderManager authenticationManager = (ProviderManager) authenticationConfiguration.getAuthenticationManager();
        log.info("{}",providers);
        authenticationManager.getProviders().addAll(providers);

        return authenticationManager;
    }

    @Autowired
    @Lazy
    AuthenticationManager authenticationManager;

    @Bean
    GuiguPickAuthenticationProcessingFilter guiguPickAuthenticationProcessingFilter(){
        GuiguPickAuthenticationProcessingFilter filter = new GuiguPickAuthenticationProcessingFilter(authenticationManager);
        filter.setAuthenticationSuccessHandler(successHandler());
        filter.setAuthenticationFailureHandler(failureHandler());
        filter.setAllowSessionCreation(false);
        return filter;
    }

    @Bean
    GuiguPickUserAuthenticationFilter guiguPickUserAuthenticationFilter(){
        return new GuiguPickUserAuthenticationFilter();
    }

    @Bean
    LogoutSuccessHandler logoutSuccessHandler(){
        return new GuiguPickLogoutSuccessHandler();
    }
    @Bean
    @Order(1)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> authorizationManager) throws Exception {

        http.authorizeHttpRequests().anyRequest().access(authorizationManager);

        http.sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.formLogin()
                .loginProcessingUrl("/login")
                .successHandler(successHandler())
                .failureHandler(failureHandler())
                .and()
                .addFilterBefore(guiguPickAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(guiguPickUserAuthenticationFilter(), LogoutFilter.class);
        http.logout()
                    .logoutSuccessHandler(logoutSuccessHandler());
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler());

        http.csrf().disable();

        return http.build();
    }

}
